<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */
// Include 
require_once 'Libs/google/src/Google_Client.php';
require_once 'Libs/google/src/contrib/Google_PlusService.php';

class Google{
    //put your code here
    public $client;
    public static $instance;
    public $nameApp = 'BuzzPulse';
    public $clientId = '208044150507.apps.googleusercontent.com';
    public $clientSecret = 'VQMiCqAtXAiP4Vz7fsXeHLui';
    public $redirectUri = 'http://pulse.ythink.net/authorizeGoogle';
    public $developerKey = 'AIzaSyBEs18RMPhavlnjenEKPhWejDrM4g55Fe4';
    public $plus;
    
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __get($name) {
        return $this->$name;
    }
    
    public function __set($name, $value) {
        $this->$name = $value;
    } 
    
    public function __construct() {
        //allocate your stuff
    }
    
    public static function withData($token = NULL){
        $instance = self::getInstance();
        $client = new Google_Client();
        $client->setApplicationName($instance->nameApp);
        $client->setClientId($instance->clientId);
        $client->setClientSecret($instance->clientSecret);
        $client->setRedirectUri($instance->redirectUri);
        $client->setDeveloperKey($instance->developerKey);
        $instance->client = $client;
        $instance->plus = new Google_PlusService($client);
        return $instance;
    }
    
    public static function getLoginURL() {
        $instance = self::withData();
        $url = $instance->client->createAuthUrl();
        return $url;
    } 
    
    public static function getAuthorization() {
        $instance = self::withData();
        $instance->client->authenticate();
        $_SESSION['token'] = $instance->client->getAccessToken();
        if (isset($_SESSION['token'])) {
            $instance->client->setAccessToken($_SESSION['token']);
        }
        if ($instance->client->getAccessToken()) {
            $_SESSION['token'] = $instance->client->getAccessToken();
            $user = $instance->plus->people->get('me');
        }
        $db = Database::getInstance();
        $id = $db->getID("googles", "id");
        $userId = User::getCurrentUserId();
        $googleid = $user['id'];
        $screenname = $user['displayName'];
        $t = split('":"|","', $_SESSION['token']);
        $oauthtoken = $t[1];
        $query = "INSERT INTO googles (id, userid, oauthtoken, googleid, 
        screenname) VALUES ('$id', '$userId', '$oauthtoken', '$googleid', '$screenname')";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            return "true";
        }
        else {
            return "false";
        }
    }
    
    public static function postStream($message){
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM twitters WHERE userid = '$userId'";
            $result = $db->query($query);
             if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow == 1) {
                    $rows = $result->dataTable->rows[0];
                    if(strlen($message) < 140){
                        $instance = self::withData($rows['oauthtoken'], $rows['oauthtokensecret']);
                        $response = $instance->tweet->post('statuses/update', array('status' => $message));                        
                        if ($response != 200) {
                            if($response == 403)
                                return "Cannot send a message twice.";
                            else
                                //Do something if the request was unsuccessful
                                return "There was an error posting the message.";
                        }
                        return "Posted";
                    }else{
                        return "The message is too long";
                    }
                }else {
                    return "Not found data";
                }
            }else {
                return "Cannot connect database";
            }
        }else {
            return "No user log in";
        }
    }
    
    public static function getGoogles() {
        if (User::getCurrentUserId()) {
            $db = Database::getInstance();
            $userId = User::getCurrentUserId();
            $query = "SELECT * FROM googles WHERE userid = '$userId'";
            $result = $db->query($query);
             if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    $username = '';
                    $userid = '';
                    foreach ($result->dataTable->rows as $row) {
                        $name = $row['screenname'];
                        $id = $row['googleid'];
                        $userid = "$userid$id;";
                        $username = "$username$name;";
                    }
                    return array(
                        "screenname" => $username,
                        "accountid" => $userid
                    );
                }else {
                    return array(
                        "screenname" => 'undefined',
                        "accountid" => 'undefined'
                    );
                }
            }else {
                return array(
                    "screenname" => 'undefined',
                    "accountid" => 'undefined'
                );
            }
        }else {
            return array(
                "screenname" => 'undefined',
                "accountid" => 'undefined'
            );
        }
    }
    
    public static function deleteGoogle($googleid) {
        if(User::getCurrentUserId()) {
            $db = Database::getInstance();
            $query = "DELETE FROM googles WHERE googleid = '$googleid'"; 
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
}
?>